package com.ly.mpayment.persist.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

import com.ly.mpayment.core.util.ListRange;
import com.ly.mpayment.persist.hibernate.HibernateDao;
import com.ly.mpayment.persist.hibernate.Page;
/**
 * 
 *
 * @param <T>
 * @param <PK>
 */
public class AbstractService<T,PK extends Serializable> extends HibernateDao<T,PK> implements IService<T,PK> {

	/**
	 * massage:数据查询失败,请稍后再试!
	 */
	public static final String FAILURE_QUERY_MASSAGE = "数据查询失败,请稍后再试!";
	/**
	 * massage:数据操作失败,请稍后再试!
	 */
	public static final String FAILURE_RUD_MASSAGE = "数据操作失败,请稍后再试!";
	/**
	 * massage:操作成功!
	 */
	public static final String SUCCESS_MASSAGE = "操作成功!";
	
	public static String PAGE_START = "start";

	public static String PAGE_LIMIT = "limit";

	/**
	 * 基于仓库猫多条件查询 查询不分页，对大数据量查询不能使用本方法。
	 * 
	 * @param name
	 *            条件名称(仓库猫)
	 * @param parameters
	 *            查询参数
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ListRange findDataByNamed(String name, Map<String,Object> parameters) {

		ListRange<T> listRange = new ListRange();
		List<T> list = null;
		try {
			list = super.findByNamed(name, parameters);
		} catch (Exception e) {
			logger.error("exception in select error ", e);
//			listRange.setMessage(FAILURE_QUERY_MASSAGE);
//			listRange.setSuccess(false);
			return listRange;
		}

		listRange.setList(list);
//		listRange.setSuccess(true);

		return listRange;

	}

	/**
	 * 基于仓库猫分页查询
	 * 
	 * @param name
	 *            条件名称(仓库猫)
	 * @param parameters
	 *            查询条件
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	
	public ListRange<T> findPageDataByNamed(String name, Map<String,Object> parameters) {

		ListRange<T> listRange = new ListRange<T>();
		try {
			Page page = super.findPageByNamed(name, parameters);
			listRange.setList(page.getResult());
//			listRange.setTotalSize(page.getTotalCount());
//			listRange.setCurrentPage(page.getPageNo());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("exception in findPage ", e);
//			listRange.setSuccess(false);
//			listRange.setMessage(FAILURE_QUERY_MASSAGE);
			return listRange;
		}

//		listRange.setSuccess(true);

		return listRange;
	}

	/**
	 * 基于仓库猫分页查询
	 * 
	 * @param name
	 *            条件名称(仓库猫)
	 * @param parameters
	 *            查询条件
	 * @param currentPage
	 *            当前页
	 * @param pageSize
	 *            单页显示记录数
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ListRange<T> findPageDataByNamed(String name, Map<String,Object> parameters,
			int start, int pageSize) {

		ListRange<T> listRange = new ListRange<T>();
		try {
			Page page = super.findPageByNamed(name, parameters, start,
					pageSize);
			listRange.setList(page.getResult());
//			listRange.setTotalSize(page.getTotalCount());
//			listRange.setCurrentPage(page.getPageNo());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("exception in findPage ", e);
			return listRange;
		}
		return listRange;
	}

	/**
	 * 根据ID查询数据 - ODBC
	 * 
	 * @param parameter
	 *            - 查询参数
	 * 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ListRange findById(Map parameter) {
		// 取得查询参数
		Set keys = parameter.keySet();
		Iterator it = keys.iterator();
		String key = "";
		Object idValue = "";
		while (it.hasNext()) {
			key = (String) it.next();
			idValue = parameter.get(key);
		}

		// 查询
		Criteria criteria = getSession().createCriteria(super.entityClass).add(
				Restrictions.eq(key, idValue));
		List list = criteria.list();

		ListRange listRange = new ListRange();
		if (list.size() != 1) {
			return listRange;
		}
		listRange.setList(list);
		return listRange;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	
    public ListRange findById(PK id) {
        T entity=super.findByUnique("id",id);
        List<T> entitys=new ArrayList<T>();
        entitys.add(entity);
        ListRange listRange = new ListRange();
		listRange.setList(entitys);
        return listRange;
    }

    /**
	 * 新增\修改
	 * 
	 * @param entity
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ListRange saveOrUpdateData(T entity) {
		ListRange listRange = new ListRange();
		try {
			T t = super.save(entity);
			this.getSession().flush();
			List<T> list = new ArrayList<T>();
			list.add(t);
			listRange.setList(list);
		} catch (Exception e) {
			logger.error("exception save failure !", e);
			return listRange;
		}

		return listRange;
	}
	



	/**
	 * 删除
	 * 
	 * @param entity
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ListRange deleteDataByEntity(T entity) {

		ListRange listRange = new ListRange();
		try {
			super.delete(entity);
		} catch (Exception e) {
			logger.error("exception in delete failure!", e);
			return listRange;
		}

		return listRange;
	}

	/**
	 * 根据ID值进行hql批量删除
	 */
	@SuppressWarnings("rawtypes")
	
	public ListRange deleteDataByIds(String name, String[] ids) {
		ListRange listRange = new ListRange();
		try {
			super.deleteByIds(name, ids);
		}catch (Exception e) {
			if(e instanceof org.hibernate.exception.ConstraintViolationException){
				logger.error("exception in delete failure!", e);
				return listRange;		
			}
			logger.error("exception in delete failure!", e);
			return listRange;
		}
		return listRange;
	}
	
	/**
	 * jiangyu
	 * 当前台转换为字符串时，删除多个ID的值可调用此方法
	 * @param ids
	 * @return 返回是否成功
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	
	public boolean deleteByIds(String ids,T entity) {
		// TODO Auto-generated method stub
		// 泛型domain对象的Class
		Class<T> entityclass = (Class<T>) entity.getClass();
		String fullClassName=entityClass.getName();
	    int pos=fullClassName.lastIndexOf(".")+1;        
	    String className = StringUtils.substring(fullClassName, pos);
		String[] idStr = null;
		String s = ",";
		if (ids.indexOf(s) >= 0) {
			idStr = ids.split(s);
		}
		StringBuilder deleteSql = new StringBuilder(
				"delete from "+className+" ");

		if (idStr != null) {
			deleteSql.append("  where id in(");
			for (int i = 0; i < idStr.length; i++) {
				deleteSql.append(idStr[i]);
				if (i != idStr.length - 1)
					deleteSql.append(",");
			}
			deleteSql.append(")");
		} else {
			deleteSql.append(" where id=" + ids + "");
		}
		logger.info(deleteSql.toString());
		Query query = this.getSession().createQuery(deleteSql.toString());
		try {
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	
	public ListRange deleteByIdWidthResult(PK id) {
		
		ListRange results = new ListRange();
		try {
			super.delete(id);
		} catch (Exception e) {
			logger.debug("exception in delete failure!", e);
			return results;
		}
		return results;
	}
	
	public boolean deleteHql(String sql){
		Query query = this.getSession().createQuery(sql);
		try {
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
